<template>
    <div class="x-login-container">
        <div class="hert" v-if="hasHertUrl"><img :src="loginBackGroupUrl"></div>
        <div class="hert" v-else :style="{backgroundImage:`url(${bgHert}) `}"></div>
        <div class="main">
            <!-- 语言切换 -->
            <div class="login-language" v-if="isI18nLang==='YES'"
                 @mouseenter="show = true" @mouseleave="show=false"
            >
                <div style="position: relative">
                    <div class="login-language-head">
                        <my-icon type="iconearth-full" style="margin-right: 5px">
                        </my-icon> {{i18nTitle}}<my-icon type="iconicon-test49" style="margin-left: 5px"></my-icon>
                    </div>
                    <div class="login-language-common" v-if="show">
                        <div class="login-language-common-list" v-for="(item,index) in i18nList" :key="item.type">
                            <div  @click="setI18nType(item.type)" class="login-language-common-list-le">{{item.name}}</div>
                            <my-icon v-if="i18nTitle===item.name" type="iconicon"></my-icon>
                        </div>
                    </div>
                </div>
            </div>
            <a-form
                id="formLogin"
                class="user-layout-login"
                ref="formLogin"
                :model="form"
                :rules="rules"
                @finish="login"
            >
                <div class="hermg"><img :src="loginPageLogoUrl"></div>
                <div class="jpaas">
                    <span>{{ loginPageTitle[lang] }}</span>
                </div>
                <div class="jpaasbutton">
                    <a-form-item style="width:100%;" name="username" >
                        <a-input size="large" type="text"
                                 :placeholder="$t('login.usernameWarning',['@'])"
                                 v-model:value="form.username"
                        >
                            <template #prefix>
                                <user-outlined :style="{ color: 'rgba(0,0,0,.25)' }" />
                            </template>
                        </a-input>
                    </a-form-item>
                    <a-form-item style="width:100%;" name="password" >
                        <a-input
                            size="large"
                            type="password"
                            autocomplete="false"
                            :placeholder="$ti18('login.passwordWarning','请输入密码')"
                            @enter="login"
                            v-model:value="form.password"
                            style="width: 100%"
                        >
                            <template #prefix>
                                <rx-icon-show icon="icon-linelock" :style="{ color: 'rgba(0,0,0,.25)' }"></rx-icon-show>
                            </template>
                        </a-input>
                    </a-form-item>
                    <a-row :gutter="8" style="width: 100%" v-if="ignoreValidCode=='false'">
                        <a-col class="gutter-row" :span="16">
                            <a-form-item name="validCode">
                                <a-input size="large" type="text" :placeholder="$ti18('login.validCode','验证码')" @enter="login"
                                         v-model:value="form.validCode"
                                >
                                    <a-icon slot="prefix" type="mail" :style="{ color: 'rgba(0,0,0,.25)' }"/>
                                </a-input>
                            </a-form-item>
                        </a-col>
                        <a-col class="gutter-row" :span="8">
                            <img class="getCaptcha" :src="codeSrc" @click="getImgCode">
                        </a-col>
                    </a-row>
                    <a-form-item style="width:100%;">
                        <a-button
                            size="large"
                            type="primary"
                            htmlType="submit"
                            class="login-button"
                            :loading="state.loginBtn"
                            :disabled="state.loginBtn">{{$ti18('login.login','登录')}}
                        </a-button>
                    </a-form-item>
                    <div style="display: flex;justify-content: space-between;">
                        <!--                    <div>-->
                        <!--                        {{$ti18('login.notregistered','新企业?')}}<a target="_blank" href="http://www.redxun.cn/jsaas/cus_reg.jsp">{{$ti18('login.freeLogon','免费试用')}}</a>-->
                        <!--                    </div>-->

                    </div>

                    <div class="footerIconBox">
                        <template v-for="item of platformIcon">
                            <div :class="['iconItem',item.cls]"
                                 @click="qrcodeLogin(item)"
                                 :title="item.name[lang]"
                            >
                            </div>
                        </template>
                    </div>
                </div>
            </a-form>
        </div>
        <div class="x-login-copyright">{{loginPageCopyright[lang]}}</div>
    </div>
</template>

<script>
import LoginApi from "@/common/api/login.js";
import SysTimeZoneConfigApi from "@/common/api/portal/timeZoneConfig.js";
import uuid from "@/common/util/uuid.js"
import { mapActions,mapState } from 'pinia'
import md5 from "js-md5";
import userUser from "../../stores/userUser";
import log from '@public/image/login/log.png'
import hert from '@public/image/login/hert.png';
import AppUtil from "../../assets/js/AppUtil";
import {TokenUtil,Util} from "@lowcode/jpaas-base-lib";
import {sm2} from 'sm-crypto';
import commonLang from "../../language/lang/common/commonLang.js";
export default {
    name: "Login",
    data(){
        return {
            rules:{
                username:[
                    { required: true, message: this.$t('login.usernameWarning',['@']) }
                ],
                password:[
                    { required: true, message: this.$ti18('login.passwordWarning','请输入密码') }
                ],
                validCode:[
                    { required: true, message: this.$ti18('login.validCode','请输入验证码','','input') }
                ]
            },
            bgHert:hert,
            defaultPlatformIcon:[
                {name:commonLang['WeChatGzh'],id:1,cls:'WeChatGzh'},
                {name:commonLang['qiyeweixin'],id:6,cls:'WeChat'},
                {name:commonLang['dingding'],id:5,cls:'dingding'},
                {name:commonLang['feishu'],id:4,cls:'feishu'}
            ],
            platformIcon:[],
            //图片的地址
            codesrc: "",

            isLoginError: false,

            form: {
                validCode:'',//验证码
                username:'', //账号
                password:'',
            },

            //是否忽略验证码

            //登录页标题
            loginPageTitle: this.$ti18('login.platform','红迅敏捷平台'),
            //登录页版权
            loginPageCopyright: '',
            //默认logo
            loginPageLogoUrl: log,
            //密码模式
            passwordmode: "default",

            state: {
                loginBtn: false,
                loginType: 0,
            },
            i18nDefault:import.meta.env.JPAAS_LANGUAGE,
            i18nTitle: this.$ti18('login.chinese','中文'),
            i18nType:"",
            i18nList:[],
            isI18nLang:import.meta.env.JPAAS_ISLANGUAGE,
            show:false,

            //登录生成的随机ID,用于生成图片
            deviceId: "",
            //验证码图片路径
            codeSrc:"",
            ignoreValidCode:'true',
            //非对称公钥
            passwordPublicKey:"",
            //跳转URL
            redirect:"",
            //国产sm2公钥
            sw2PublicKey:import.meta.env.JPAAS_SM2_PUBLIC_KEY,
            //租户信息
            sitettingJson:{},
            //是否租户登录
            isTenantLogin:false,
            //是否有在线登录背景图
            hasHertUrl:false,
            //默认logo
            loginBackGroupUrl: "",
            tenantId:"",
            //域名值
            hostName:"",
            lang:'zh-CN'
        }
    },
    computed:{
        ...mapState(userUser, ['isFirstLogin']),
    },
    created() {
        this.lang = window.localStorage.getItem('language') || 'zh-CN';
        //取跳转URL
        if (this.$route.query && this.$route.query.redirect) {
            this.redirect = this.$route.query.redirect;
        }
        this.getTenantByUrl();
        //获取验证码
        this.getImgCode();
        //获取登录相关的配置参数
        this.getLoginConfig();

        this.autoRedirect();

        //设置当前登录为主界面登录
        Util.setKeyVal("loginFrom", "main_");
    },
    methods: {
        ...mapActions(userUser, ['setPasswordMode', 'setSiteName', 'Login']),
        //二维码登录
        qrcodeLogin(item) {
            let query = {
                loginType: item.id,
                tenantId: this.tenantId,
                hostName: this.hostName
            }
            this.$router.push({name: 'qrcodeLogin', query: query});
        },
        //获取验证码
        async getImgCode() {
            this.deviceId = uuid.uuid(16, 32);
            await LoginApi.imgcode(this.deviceId).then(res => {
                const raw = res.data
                this.codeSrc = URL.createObjectURL(raw)
            })
        },
        getJSEncryptPassword(password) {
            // 新建JSEncrypt对象
            let encryptor = new JSEncrypt();
            encryptor.setPublicKey(this.passwordPublicKey);
            let jm_data = encryptor.encrypt(password);
            // 加密数据
            return jm_data;
        },
        setI18nType(type) {
            this.lang = type;
            this.i18nType = type;
            this.$i18n.locale = type;
            let obj = this.i18nList.find(row => type === row.type);
            if (obj) {
                this.i18nTitle = obj.name;
            }
            AppUtil.setLanguage(type);
        },
        initI18n() {
            let language = AppUtil.getLanguage();
            if (!language) {
                this.setI18nType(this.i18nDefault);
                return;
            }
            this.setI18nType(language);
        },
        getConfig(config) {
            if (!config) {
                return {}
            }
            return new Function(`return ${config}`)()
        },
        //获取登录相关的配置参数
        async getLoginConfig() {
            let self = this;
            await LoginApi.getLoginConfig(this.hostName).then((res) => {
                let result = res.data;

                //多语言。
                self.i18nList = result.multiLinguals;
                window.localStorage.setItem("i18nList", JSON.stringify(result.multiLinguals));
                self.initI18n();

                self.initTenantInfo(result);
                //密码加密模式
                self.setPasswordMode(result.passwordmode);
                self.passwordmode = result.passwordmode;
                self.passwordPublicKey = result.passwordPublicKey;

                // 获取已配置的平台列表
                let platformList = result.platformList;
                if (platformList && platformList.length > 0) {
                    self.platformIcon = self.defaultPlatformIcon.filter(platform => platformList.includes(platform.cls));
                }

            });
        },
        initTenantInfo(result) {
            let self = this;
            if (result.sitettingJson) {

                if (result.sitettingJson.tenantId && result.sitettingJson.tenantId != "1") {
                    self.tenantId = result.sitettingJson.tenantId;
                    self.isTenantLogin = true;
                }

                self.sitettingJson = JSON.parse(result.sitettingJson.confs);

                self.ignoreValidCode = self.sitettingJson.ignoreValidCode;


                if (self.sitettingJson.loginPageConfig) {
                    var loginPageConfig = self.sitettingJson.loginPageConfig;

                    self.loginPageTitle = self.getConfig(loginPageConfig.loginPageTitle)

                    let loginPageCopyright = self.getConfig(loginPageConfig.loginPageCopyright)
                    self.loginPageCopyright = loginPageCopyright
                    //设置标题
                    self.setSiteName(self.getConfig(self.sitettingJson.homePageTitle))
                    document.title = self.$i18(self.loginPageTitle, "登录页标题国际化")
                    localStorage.setItem("siteName", JSON.stringify(self.getConfig(self.sitettingJson.homePageTitle)));
                    if (loginPageConfig.loginPageLogo) {
                        self.loginPageLogoUrl = self.getFilePath(loginPageConfig.loginPageLogo);
                    }
                    if (loginPageConfig.loginBackGroup) {
                        self.hasHertUrl = true;
                        self.loginBackGroupUrl = self.getFilePath(loginPageConfig.loginBackGroup);
                    }
                }
                localStorage.setItem("linkLogoUrl", self.sitettingJson.linkLogoUrl);
            } else {
                //是否显示验证码
                self.ignoreValidCode = result.ignoreValidCode;

                if (result.loginPageConfig) {
                    let loginPageConfig = self.getConfig(result.loginPageConfig)

                    self.loginPageTitle = self.getConfig(loginPageConfig.loginPageTitle)

                    let loginPageCopyright = self.getConfig(loginPageConfig.loginPageCopyright)
                    self.loginPageCopyright = loginPageCopyright
                    //设置标题
                    self.setSiteName(self.getConfig(result.homePageTitle))
                    document.title = self.$i18(self.loginPageTitle, "登录页标题国际化")
                    localStorage.setItem("siteName", JSON.stringify(self.getConfig(result.homePageTitle)));
                    if (loginPageConfig.loginPageLogo) {
                        self.loginPageLogoUrl = self.getFilePath(loginPageConfig.loginPageLogo);
                    }
                }
                localStorage.setItem("linkLogoUrl", self.sitettingJson.linkLogoUrl || "");
            }
        },
        getTenantByUrl() {
            this.hostName = window.location.hostname;
        },
        getFilePath(fileId) {
            return "/api/api-system/system/core/sysFile/public/download/" + fileId;
        },
        sm2Encrypt(password) {
            let pwd = sm2.doEncrypt(password, this.sw2PublicKey);
            return pwd.toString();
        },
        checkUserName(username) {
            let res = {
                status: true,
                userName: ""
            }
            if (!username || !username.trim()) {
                return res;
            }

            let tenantName = username.trim();
            if (!this.isTenantLogin) {
                res.userName = tenantName;
                return res;
            }

            if (tenantName.indexOf("@") > -1) {
                let names = tenantName.split("@");
                if (!names[0]) {
                    this.$message.error(this.$ti18('login.messageInfo.nameNotEmpty', "登录名@字符串前的登录名不能为空!"));
                    res.status = false;
                    return res;
                } else if (!names[1]) {
                    res.userName = names[0] + "@" + this.hostName;
                    return res;
                } else if (names[1] != this.hostName) {
                    this.$message.error("@" + this.$ti18('login.messageInfo.notHostName', '后面的字符串不等于域名') + "【" + this.hostName + "】!");
                    res.status = false;
                    return res;
                }
                res.userName = tenantName;
                return res;
            } else {
                if (this.isTenantLogin) {
                    res.userName = tenantName + "@" + this.hostName;
                } else {
                    res.userName = tenantName;
                }
            }
            return res;
        },
        //登录
        login(e) {
            this.state.loginBtn = true;
            //租户校验登录名
            let res = this.checkUserName(this.form.username);
            if (!res.status) {
                return;
            }

            let loginParams = {
                username: res.userName,
                deviceId: this.deviceId,
                validCode: this.form.validCode,
                password: this.form.password.trim()
            }

            if (this.isTenantLogin) {
                loginParams.tenantId = this.tenantId;
            }

            if (this.passwordPublicKey) {
                loginParams.password = this.getJSEncryptPassword(this.form.password.trim());
            } else if ("md5" === this.passwordmode) {
                loginParams.password = md5(this.form.password.trim())
            } else if ("sm2" === this.passwordmode) {
                loginParams.password = this.sm2Encrypt(this.form.password.trim())
            }
            let self = this;
            this.Login(loginParams, function (res, err) {
                if (!err) {
                    self.loginSuccess(res);
                } else {
                    self.requestFailed(err)
                }
            })
        },
        //登录成功处理
        loginSuccess(res) {
            this.state.loginBtn = false;
            if (res.code === 200) {
                // document.title = JSON.parse(localStorage.getItem("siteName") || "{}")[localStorage.getItem('language') || 'zh-CN'] || "敏捷开发平台";
                //存在需要跳转的URL,则跳转到指定的URL
                this.getMainInfo();
                this.redirectTo();
            } else {
                this.requestFailed(res)
            }
        },
        //登录失败处理
        requestFailed(err) {
            this.state.loginBtn = false;
            this.getImgCode()
        },
        /**
         * 如果有redirect就跳转，否则跳转到首页.
         */
        redirectTo() {
            this.$router.push({name: 'appHome'}, () => {
            })
        },
        /**
         * 如果首页存在则自动跳转.
         */
        autoRedirect() {
            let token = TokenUtil.getToken();
            if (!token) {
                return;
            }
            this.redirectTo()
        },
        async getMainInfo(){
            let {data} = await SysTimeZoneConfigApi.getHomeConfig();
            if(data.confs){
                let confs = JSON.parse(data.confs);
                let title = JSON.parse(confs.homePageTitle)[this.lang];
                document.title = title || "敏捷平台";
            }

        }
    }
}
</script>

<style scoped>
.login-modal {
    text-align: center;
}

.login-qrcode {
    width: 160px;
    height: 160px;
    margin: auto;
}

.login-qrcode img {
    object-fit: scale-down;
    width: 100%;
}

.x-login-copyright {
    text-align: center;
    position: absolute;
    bottom: 20px;
    width: 100%;
    color: #fff;
}

.hert {
    position: absolute;
    max-width: 43.2%;
    width: 100%;
    height: 0;
    padding-bottom: 36.54%;
    top: 50%;
    left: 10%;
    transform: translate(0, -50%);
    -webkit-transform: translate(0, -50%);
    -ms-transform: translate(0, -50%);
    -moz-transform: translate(0, -50%);
    z-index: 1;
    background-position: 20% center;
    background-repeat: no-repeat;
    background-size: contain;
}
.hert img{
    max-width: 100%;
}
.x-login-container {
    width: 100%;
    min-height: 100%;
    background: -webkit-gradient(linear, right top, left bottom, from(#409eff), to(#99aefd));
    background: linear-gradient(to left bottom, #409eff, #99aefd);
    background-size: 100%;
    position: relative;
    display: flex;
}

.login-container {
    width: 600px;
    margin: 40px auto;
}

.login-language-common {
    min-width: 140px;
    background: #FFFFFF;
    box-shadow: 0px 0px 10px 1px rgba(0, 0, 0, 0.08);
    border-radius: 4px 4px 4px 4px;
    position: absolute;
    top: 30px;
    right: 0px;
    padding: 10px 0px;
    z-index: 9999;
}

.login-language-common-list {
    height: 32px;
    align-items: center;
    display: flex;
    cursor: pointer;
    padding: 0px 5px;
    margin: 0px 5px;
    border-right: 2px;

}

.login-language-common-list i {
    color: #1890FF;
    font-size: 18px;
}

.login-language-common-list:hover {
    background: rgba(24, 144, 255, 0.1);
}

.login-language-common-list-le {
    flex: 1;
    font-weight: 400;
    color: #29304C;
    font-size: 14px;
}

.login-language {
    position: absolute;
    top: 30px;
    right: 30px;
}

.login-language-head {
    display: flex;
    align-items: center;
    cursor: pointer;
    height: 30px;
    color: #666666;
    font-size: 14px;
    margin-top: 27px;
    margin-right: 15px;
}

.otherLogin {
    text-align: center;
    padding: 4px 0;
    margin-top: 18px;
    position: relative;
}

.otherLogin:after,
.otherLogin:before {
    content: '';
    position: absolute;
    top: 50%;
    margin-top: 1px;
    width: 38%;
    height: 1px;
}

.otherLogin:after {
    left: 0;
    background: linear-gradient(270deg, #D9D9D9 0%, #FFFFFF 100%);
}

.otherLogin:before {
    right: 1px;
    background: linear-gradient(90deg, #D9D9D9 0%, #FFFFFF 100%);
}

.footerIconBox {
    text-align: center;
    font-size: 0;
}

.iconItem {
    display: inline-block;
    width: 40px;
    height: 40px;
    border-radius: 50%;
    margin: 16px 20px 0;
}

.feishu {
    background: url("@public/image/login/fs.png") no-repeat;
}

.WeChat {
    background: url("@public/image/login/qywx.png") no-repeat;
}

.WeChatGzh {
    border: 1px solid rgb(234, 234, 234);
    background: url("@public/image/login/gzh.png") no-repeat center center;
}

.dingding {
    background: url("@public/image/login/dd.png") no-repeat;
}

.wxspan {
    margin-top: 5px;
    line-height: 14px;
    padding-right: 10px;
}

.bblict {
    display: inline-block;
    width: 25px;
    height: 25px;
    border-radius: 50%;
}


.main {
    padding: 20px 40px;
    overflow: hidden;
    width: 440px !important;
    background-color: #ffffff;
    box-shadow: 0px 0px 49px 0px rgba(7, 63, 126, 0.24);
    border-radius: 16px;
    position: absolute;
    top: 50%;
    -webkit-transform: translateY(-50%);
    transform: translateY(-50%);
    right: 10%;
    z-index: 9;
}

.hermg {
    width: 54px;
    margin: auto;
    margin-top: 24px;

}

.hermg img {
    width: 54px;
}

.jpaas {
    margin-top: 10px;
    font-size: 20px;
    color: #29304C;
    font-weight: bold;
    text-align: center;
}

.jpaasbutton {
    overflow: hidden;
    margin: auto;
    margin-top: 16px;
    padding-bottom: 30px;
}

.imgwing img {
    width: 100%;
    height: 40px;
}

.ant-tabs-nav-wrap {
    border-bottom: 1px solid #eeeeee !important;
}

label {
    font-size: 14px;
}

.getCaptcha {
    display: block;
    width: 100%;
    height: 40px;
}

.forge-password {
    font-size: 14px;
}

button.login-button {
    padding: 0 10px;
    font-size: 16px;
    height: 40px;
    width: 100%;
}

.user-login-other {
    text-align: left;
    margin-top: 24px;
    line-height: 22px;
}

.item-icon {
    font-size: 24px;
    color: rgba(0, 0, 0, 0.2);
    margin-left: 16px;
    vertical-align: middle;
    cursor: pointer;
    transition: color 0.3s;


}

.item-icon:hover {
    color: #1890ff;
}

.register {
    float: right;
}

</style>
